<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\LocationService;
use app\admin\service\MarketingPathService;
use app\admin\service\MarketingService;
use app\admin\service\MarketingUsersService;
use app\admin\service\OfficialStaffService;
use app\admin\service\UsersService;
use app\AdminController;
use qrcode\QrcodeServer;
use think\exception\ValidateException;
use app\admin\validate\Marketing as MarketingValidate;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

/**
 * 营销活动
 * Class Marketing
 * @package app\admin\controller
 */
class Marketing extends AdminController
{
    /**
     * 营销活动列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $user_auth = session('user_auth');
        // 登录账号是？？？
        // 超管、管理员
        if (in_array($user_auth['role'], [1, 6])) {
            // 默认查询全部
            $manager = intval($this->request->param('manager', 0));
            // 查询对应的登录用户数据
        } else {
            // 获取营销活动人员id
            $manager = intval($user_auth['manager']);
        }


        $where = [];
        // 全部页
        $view = 'index';
        // 转换用户
        $areaIdentityWhere = ['m.is_convert' => 1];
        // 8.8月会员
        $monthWhere = ['o.type_id' => 1, 'o.mid' => 3];
        // 108年会员
        $yearWhere = ['o.type_id' => 1, 'o.mid' => 1];
        // 499社群礼包
        $resourceWhere = ['o.type_id' => 15];

        // 营销活动工作人员
        $officialStaff = OfficialStaffService::getOfficialStaff(3);

        // 查询某工作人员下的用户数据
        if ($manager) {
            // 用户页
            $view = 'user_index';
            $where[] = ['m.manager', '=', $manager];

            // 小程序用户查询条件
            $appletsWhere = ['u.associate' => 2, 'm.manager' => $manager];
            // 所有端活动用户总数
            $totalUsers = MarketingUsersService::totalAllMarketingUsers(['manager' => $manager]);
            // 小程序用户总数
            $appletsTotalUsers = MarketingUsersService::totalOtherMarketingUsers($appletsWhere);
            // 实时访问
            $appletsTodayUsers = MarketingUsersService::todayMarketingUsers($appletsWhere);
            // 昨日访问
            $appletsYesTodayUsers = MarketingUsersService::yesTodayMarketingUsers($appletsWhere);
            // 本月访问
            $appletsMonthUsers = MarketingUsersService::monthMarketingUsers($appletsWhere);

            // H5用户查询条件
            $h5Where = ['u.associate' => 1, 'm.manager' => $manager];
            // H5用户总数
            $h5TotalUsers = MarketingUsersService::totalOtherMarketingUsers($h5Where);
            // 实时访问
            $h5TodayUsers = MarketingUsersService::todayMarketingUsers($h5Where);
            // 昨日访问
            $h5YesTodayUsers = MarketingUsersService::yesTodayMarketingUsers($h5Where);
            // 本月访问
            $h5MonthUsers = MarketingUsersService::monthMarketingUsers($h5Where);

            // 直属用户总数
            $underTotalUsers = MarketingUsersService::totalOtherMarketingUsers($where);
            // 营业金额
            $underUsersPrice = MarketingUsersService::sumMarketingUsersPrice($where);
            // 直属营业总额
            $underTotalPrice = round($underUsersPrice);

            // 总营业额
            $totalPrice = sprintf("%.2f", $underUsersPrice);
            // 提成点
            $commission_ratio = OfficialStaffService::findOfficialStaffValue(['id' => $manager], 'commission_ratio');
            // 所得佣金
            $commission = $underUsersPrice * $commission_ratio;
            // 总营业额（折线图）
            $underUsersPriceLine = MarketingUsersService::getMarketingUsersPriceLine($where);

            // 8.8月会员
            // 108年会员
            // 499社群礼包
            // 下单地区、下单身份
            $areaIdentityWhere['m.manager'] = $resourceWhere['m.manager'] = $yearWhere['m.manager'] = $monthWhere['m.manager'] = $manager;

            $viewData = [
                'applets' => [
                    'appletsTotalUsers' => $appletsTotalUsers,
                    'appletsLastTotalUsers' => $totalUsers - $appletsTotalUsers,
                    'appletsTodayUsers' => $appletsTodayUsers,
                    'appletsYesTodayUsers' => $appletsYesTodayUsers,
                    'appletsMonthUsers' => $appletsMonthUsers,
                ],
                'h5' => [
                    'h5TotalUsers' => $h5TotalUsers,
                    'h5LastTotalUsers' => $totalUsers - $h5TotalUsers,
                    'h5TodayUsers' => $h5TodayUsers,
                    'h5YesTodayUsers' => $h5YesTodayUsers,
                    'h5MonthUsers' => $h5MonthUsers,
                ],
                'under' => [
                    'underTotalUsers' => $underTotalUsers,
                    'underTotalPrice' => $underTotalPrice,
                    'totalPrice' => $totalPrice,
                    'commission_ratio' => ($commission_ratio * 100) . '%',
                    'commission' => sprintf("%.2f", $commission),
                    'underUsersPriceLine' => $underUsersPriceLine,
                ]
            ];

            // 全部
        } else {
            // 用户总数
            $totalUsers = UsersService::countUsers();
            // 部门直属用户
            $underUsers = MarketingUsersService::getDepartmentDirectUsers();
            // 其他来源用户
            $otherUsers = MarketingUsersService::otherMarketingUsers();
            // 用户总数（折线图）
            $usersMonthLine = UsersService::getUsersMonthLine();
            // 部门直属用户（折线图）
            $marketingUsersMonthLine = MarketingUsersService::getMarketingUsersMonthLine();
            // 部门营业金额
            $totalUsersPrice = MarketingUsersService::sumMarketingUsersPrice();

            // 部门总营业额
            $totalPrice = sprintf("%.2f", $totalUsersPrice);
            // 提成点（先恒定全部人都是这个）
            $commission_ratio = 0.1;
            // 所得佣金
            $commission = $totalUsersPrice * $commission_ratio;
            // 部门总营业额（折线图）
            $underUsersPriceLine = MarketingUsersService::getMarketingUsersPriceLine();

            $viewData = [
                'users' => [
                    'totalUsers' => $totalUsers,
                    'underUsers' => $underUsers,
                    'otherUsers' => $otherUsers,
                    'usersMonthLine' => $usersMonthLine,
                    'marketingUsersMonthLine' => $marketingUsersMonthLine,
                ],
                'under' => [
                    'totalPrice' => $totalPrice,
                    'commission_ratio' => ($commission_ratio * 100) . '%',
                    'commission' => sprintf("%.2f", $commission),
                    'underUsersPriceLine' => $underUsersPriceLine,
                ],
            ];
        }

        // 8.8月会员（折线图）
        $monthLine = MarketingUsersService::getMarketingOrderLine($monthWhere);
        // 8.8月会员营业额
        $monthUsersPrice = MarketingUsersService::getMarketingOrderPrice($monthWhere);
        // 8.8月会员复购比例
        $monthRepurchaseRatio = '3%';

        // 108年会员（折线图）
        $yearLine = MarketingUsersService::getMarketingOrderLine($yearWhere);
        // 108年会员营业额
        $yearUsersPrice = MarketingUsersService::getMarketingOrderPrice($yearWhere);
        // 108年会员复购比例
        $yearRepurchaseRatio = '3%';

        // 社群礼包（折线图）
        $resourceLine = MarketingUsersService::getMarketingOrderLine($resourceWhere);
        // 社群礼包营业额
        $resourceUsersPrice = MarketingUsersService::getMarketingOrderPrice($resourceWhere);
        // 社群礼包复购比例
        $resourceRepurchaseRatio = '3%';

        // 下单地区分布
        $areaData = MarketingUsersService::getMarketingOrderArea($areaIdentityWhere);
        // 下单身份数据
        $identityData = MarketingUsersService::getMarketingOrderIdentity($areaIdentityWhere);

        $viewData['monthMember'] = [
            'monthLine' => $monthLine,
            'monthUsersPrice' => $monthUsersPrice,
            'monthRepurchaseRatio' => $monthRepurchaseRatio,
        ];
        $viewData['yearMember'] = [
            'yearLine' => $yearLine,
            'yearUsersPrice' => $yearUsersPrice,
            'yearRepurchaseRatio' => $yearRepurchaseRatio,
        ];
        $viewData['resourcePack'] = [
            'resourceLine' => $resourceLine,
            'resourceUsersPrice' => $resourceUsersPrice,
            'resourceRepurchaseRatio' => $resourceRepurchaseRatio,
        ];
        $viewData['resourcePack'] = [
            'resourceLine' => $resourceLine,
            'resourceUsersPrice' => $resourceUsersPrice,
            'resourceRepurchaseRatio' => $resourceRepurchaseRatio,
        ];
//        var_dump($areaData);exit;
        $viewData['areaData'] = $areaData;
        $viewData['identityData'] = $identityData;
        if (request()->isPost()) {
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            if ($keywords) {
                $where[] = ['m.title|o.manager_name', 'like', '%' . $keywords . '%'];
            }

            $list = MarketingService::getMarketingList($where, $this->page, $this->pagesize);
            $count = MarketingService::countMarketingList($where);

            return adminResponseJson([
                'list' => $list,
                'count' => $count
            ]);
        }

        return view($view, [
            'officialStaff' => $officialStaff,
            'manager' => $manager,
            'userRole' => $user_auth['role'],
            'viewData' => $viewData
        ]);
    }

    /**
     * 新用户/转换用户
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function marketingUsers()
    {
        if (request()->isPost()) {
            // 活动id
            $mid = intval($this->request->param('mid', 0));
            if (!$mid) {
                $this->error(adminJsonMsg(1001));
            }
            // 0新用户  1转换用户
            $type = intval($this->request->param('type', 0));
            // 关键词搜索
            $keywords = trim($this->request->param('keywords', ''));
            $where[] = ['m.mid', '=', $mid];
            if ($type) {
                $where[] = ['m.is_convert', '=', $type];
            }
            if ($keywords) {
                $where[] = ['m.associate|u.nickname', 'like', '%' . $keywords . '%'];
            }

            $list = MarketingUsersService::getMarketingUsers($where, $this->page, $this->pagesize);
            $count = MarketingUsersService::countMarketingUsers($where);

            return adminResponseJson([
                'list' => $list,
                'count' => $count
            ]);
        }
    }

    /**
     * 活动添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function marketingAdd()
    {
        if (request()->isPost()) {
            $data = $this->request->post();
            try {
                validate(MarketingValidate::class)->marketingInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['start_time'] = strtotime(date('Y-m-d H:i', strtotime($data['start_time'])));
            $data['end_time'] = strtotime(date('Y-m-d H:i', strtotime($data['end_time'])));

            // 启动事务
            Db::startTrans();
            try {
                $res = MarketingService::createMarketing($data);
                if (!$res) {
                    $this->error(adminJsonMsg(1003));
                }

                // 生成二维码
                $file_name = './public/qrcode/marketingCode';  // 定义保存目录
                $config['file_name'] = $file_name;
                // 二维码大小
                $config['size'] = 350;
                $qr_code = new QrcodeServer($config);
                // https://api.xnm3000.cn 该域名需到小程序后台->开发->开发管理->开发设置->扫普通链接二维码打开小程序  里面添加
                $url = 'https://api.xnm3000.cn?marketing_id=' . $res->id . '&manager=' . $res->manager;
                $qrRes = $qr_code->createServer($url);
                if ($qrRes['success'] == false) {
                    $this->error(adminJsonMsg(10017));
                }
                // 更新二维码
                $qrcode = str_replace('\\', '/', ltrim($qrRes['data']['url'], '.'));
                $res = MarketingService::updateMarketing(['qrcode' => $qrcode], ['id' => $res->id]);

                $filesArr = $data['files'] ? explode(',', $data['files']) : [];
                if ($filesArr) {
                    // 存储图片/视频路径到指定表
                    foreach ($filesArr as $files) {
                        $original_name = Cache::get($files);
                        Log::write('addGetCache' . $original_name, 'error');
                        MarketingPathService::createMarketingPath([
                            'path' => $files,
                            'original_name' => $original_name,
                            'mid' => $res->id,
                        ]);

                        Log::write('addDeleteCacheKey' . $files, 'error');
                        Cache::delete($files);

                    }
                }

                // 存储文件到阿里云
                $filesArr[] = $qrcode;
                AliOosService::uploadAliOos($filesArr);

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }

            $this->success(adminJsonMsg(1004), (STRING)url('/marketing/index'));
        }

        // 超管、管理员
        $userAuth = session('user_auth');
        $officialStaff = $userAuth['manager'];
        // 查询所有营销活动人员
        if (in_array($userAuth['role'], [1, 6])) {
            // 经办人查询条件  1市场需求  2涨知识  3营销活动
            $officialStaff = OfficialStaffService::getOfficialStaff(3);
        }

        // 省份
        $province = LocationService::getProvince();
        return view('', ['officialStaff' => $officialStaff, 'province' => $province, 'userRole' => $userAuth['role']]);
    }

    /**
     * 活动编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function marketingEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = MarketingService::findMarketing(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
        $info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);

        // 活动文件
        $marketingPath = MarketingPathService::getMarketingPath(['mid' => $id]);
        $info['filesPath'] = $marketingPath['path']['filesPath'];
        $info['marketingPath'] = $marketingPath['path']['marketingPath'];

        if (request()->isPost()) {
            $data = $this->request->post();

            try {
                validate(MarketingValidate::class)->marketingEdit()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['start_time'] = strtotime(date('Y-m-d H:i', strtotime($data['start_time'])));
            $data['end_time'] = strtotime(date('Y-m-d H:i', strtotime($data['end_time'])));

            // 启动事务
            Db::startTrans();
            try {

                $res = MarketingService::updateMarketing($data, ['id' => $data['id']]);
                if (!$res) {
                    $this->error(adminJsonMsg(1003));
                }

                $filesArr = $data['files'] ? explode(',', $data['files']) : [];
                // 比对是否新增了文件
                $filesPathArr = array_diff($filesArr, $marketingPath['yFilesArr']);
                if ($filesPathArr) {
                    // 存储文件路径
                    foreach ($filesPathArr as $files) {
                        $original_name = Cache::get($files);
                        Log::write('editGetCache' . $original_name, 'error');
                        MarketingPathService::createMarketingPath([
                            'path' => $files,
                            'original_name' => $original_name,
                            'mid' => $res->id,
                        ]);

                        Log::write('editDeleteCacheKey' . $files, 'error');
                        Cache::delete($files);
                    }

                    AliOosService::uploadAliOos($filesArr);
                }

                // 比对是否删除了文件
                $delFilesPathArr = array_diff($marketingPath['yFilesArr'], $filesArr);
                // 删除文件所在表
                if ($delFilesPathArr) {
                    foreach ($delFilesPathArr as $path) {
                        MarketingPathService::delMarketingPath(['mid' => $data['id'], 'path' => $path]);
                    }
                }

                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }

            $this->success(adminJsonMsg(1004), (STRING)url('/marketing/index'));
        }

        // 超管、管理员
        $userAuth = session('user_auth');
        $officialStaff = $userAuth['manager'];
        // 查询所有营销活动人员
        if (in_array($userAuth['role'], [1, 6])) {
            // 经办人查询条件  1市场需求  2涨知识  3营销活动
            $officialStaff = OfficialStaffService::getOfficialStaff(3);
        }
        // 省份
        $province = LocationService::getProvince();
        // 城市
        $city = LocationService::getCity($info['province']);
        // 地区
        $area = LocationService::getArea($info['city']);
        return view('', [
            'info' => $info,
            'officialStaff' => $officialStaff,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'userRole' => $userAuth['role']
        ]);
    }

    /**
     * 活动详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function marketingShow()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = MarketingService::findMarketing(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }

        $info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
        $info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);

        // 活动文件
        $marketingPath = MarketingPathService::getMarketingPath(['mid' => $id]);
        $info['filesPath'] = $marketingPath['path']['filesPath'];
        $info['marketingPath'] = $marketingPath['path']['marketingPath'];

        // 经办人
        $info['manager'] = OfficialStaffService::findOfficialStaffValue(['id' => $info['manager']], 'alias');
        // 省份
        $info['province'] = LocationService::getLocationValue(['location_id' => $info['province']]);
        // 城市
        $info['city'] = LocationService::getLocationValue(['location_id' => $info['city']]);
        // 地区
        $info['area'] = LocationService::getLocationValue(['location_id' => $info['area']]);
        return view('', ['info' => $info]);
    }
}